<template>
  <div class="car-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>车辆信息管理</span>
          <el-button type="primary" @click="handleAdd">添加车辆</el-button>
        </div>
      </template>

      <el-table :data="carList" style="width: 100%">
        <el-table-column prop="id" label="车辆ID" width="100" />
        <el-table-column prop="brand" label="品牌" width="120" />
        <el-table-column prop="model" label="型号" width="120" />
        <el-table-column prop="plateNumber" label="车牌号" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastMaintenance" label="上次保养" width="180" />
        <el-table-column prop="nextMaintenance" label="下次保养" width="180" />
        <el-table-column prop="mileage" label="里程数" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div style="display: flex; gap: 5px;">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加车辆' : '编辑车辆'"
      width="500px"
    >
      <el-form :model="carForm" label-width="100px" :rules="rules" ref="carFormRef">
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="carForm.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="carForm.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="车牌号" prop="plateNumber">
          <el-input v-model="carForm.plateNumber" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="carForm.status" placeholder="请选择状态">
            <el-option label="可用" :value="1" />
            <el-option label="租出" :value="2" />
            <el-option label="维修" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="上次保养" prop="lastMaintenance">
          <el-date-picker
            v-model="carForm.lastMaintenance"
            type="date"
            placeholder="选择上次保养日期"
          />
        </el-form-item>
        <el-form-item label="下次保养" prop="nextMaintenance">
          <el-date-picker
            v-model="carForm.nextMaintenance"
            type="date"
            placeholder="选择下次保养日期"
          />
        </el-form-item>
        <el-form-item label="里程数" prop="mileage">
          <el-input-number v-model="carForm.mileage" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const carList = ref([])

// 获取车辆列表
const fetchCarList = async () => {
  console.log('开始获取车辆列表...')
  try {
    const token = localStorage.getItem('Token')
    const response = await fetch(`http://localhost:8080/car/list?page=${currentPage.value}&size=${pageSize.value}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      // token 过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('获取车辆列表成功，原始数据：', result)
    
    if (result.code === 200) {
      carList.value = result.data.records || []
      total.value = result.data.total || 0
      console.log('处理后的车辆列表数据：', carList.value)
    } else {
      throw new Error(result.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取车辆列表失败：', error)
    ElMessage.error('获取车辆列表失败：' + error.message)
  }
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCarList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchCarList()
}

// 在组件挂载时获取车辆列表
onMounted(() => {
  console.log('组件已挂载，准备获取车辆列表')
  fetchCarList()
})

const dialogVisible = ref(false)
const dialogType = ref('add')
const carFormRef = ref(null)
const carForm = reactive({
  brand: '',
  model: '',
  plateNumber: '',
  status: 1,
  lastMaintenance: '',
  nextMaintenance: '',
  mileage: 0
})

const rules = {
  brand: [{ required: true, message: '请输入品牌', trigger: 'blur' }],
  model: [{ required: true, message: '请输入型号', trigger: 'blur' }],
  plateNumber: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(carForm, {
    brand: '',
    model: '',
    plateNumber: '',
    status: 1,
    lastMaintenance: '',
    nextMaintenance: '',
    mileage: 0
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 创建一个新对象，避免直接修改原始数据
  const formData = {
    ...row,
    status: Number(row.status) // 确保status是数字类型
  }
  Object.assign(carForm, formData)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该车辆吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const token = localStorage.getItem('Token')
      const response = await fetch(`http://localhost:8080/car/delete/${row.id}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Token': token
        }
      })

      if (response.status === 401) {
        // token 过期或无效，清除本地存储并跳转到登录页
        localStorage.removeItem('Token')
        localStorage.removeItem('user')
        window.location.href = '/login'
        return
      }

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      const result = await response.json()
      if (result.code === 200) {
        ElMessage.success('删除成功')
        // 刷新列表
        fetchCarList()
      } else {
        throw new Error(result.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败：', error)
      ElMessage.error('删除失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消删除操作
    ElMessage.info('已取消删除')
  })
}

const handleSubmit = async () => {
  if (!carFormRef.value) return
  
  await carFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const token = localStorage.getItem('Token')
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8080/car/add'
          : 'http://localhost:8080/car/update'
        
        const response = await fetch(url, {
          method: dialogType.value === 'add' ? 'POST' : 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Token': token
          },
          body: JSON.stringify(carForm)
        })

        if (response.status === 401) {
          // token 过期或无效，清除本地存储并跳转到登录页
          localStorage.removeItem('Token')
          localStorage.removeItem('user')
          window.location.href = '/login'
          return
        }

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
          dialogVisible.value = false
          // 刷新列表
          fetchCarList()
        } else {
          throw new Error(result.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败：', error)
        ElMessage.error('操作失败：' + error.message)
      }
    }
  })
}

// 状态映射
const statusMap = {
  1: '可用',
  2: '租出',
  3: '维修'
}

// 获取状态类型
const getStatusType = (status) => {
  const statusTypeMap = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return statusTypeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status] || '未知'
}
</script>

<style scoped>
.car-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 